import { useState } from "react";
import { useBoolean } from "ahooks";
import Taro, { useRouter } from "@tarojs/taro";
import { PageContainer, Picker, View } from "@tarojs/components";

import ByTag from "@/components/ui/ByTag";
import Page from "@/components/common/Page";
import ByCell from "@/components/ui/ByCell";
import Card from "@/components/common/Card";
import ByText from "@/components/ui/ByText";
import ByIcon from "@/components/ui/ByIcon";
import BySpace from "@/components/ui/BySpace";
import ByButton from "@/components/ui/ByButton";
import Uploader from "@/components/app/Uploader";
import ByStepsItem from "@/components/ui/ByStepsItem";
import FormInput from "@/components/common/FormInput";
import ByCellGroup from "@/components/ui/ByCellGroup";
import PopupMember from "@/components/app/PopupMember";
import ByImageGroup from "@/components/ui/ByImageGroup";
import FormInputNumber from "@/components/common/FormInputNumber";

import ApiCrm from "@/api/crm";
import ApiFinance from "@/api/finance";
import useForm from "@/hooks/useForm";
import useFetch from "@/hooks/useFetch";
import useWorkflowDefinition from "@/hooks/useWorkflowDefinition";

import { Supplier, UserInfo, Worker } from "@/types/work";
import { IntentCustomerData } from "@/types/customer";

// 0:施工人员,1:供应商，2:
const tabItems = [
  { label: "施工人员", value: 0, key: "erp" },
  { label: "供应商", value: 1, key: "supplier" },
  { label: "工人", value: 2, key: "worker" },
] as const;

type FormModel = {
  /**
   * 施工记录主表ID
   */
  constructionRecordMainId?: number;
  /**
   * 文件引用ID
   */
  fileRefererId?: string;
  /**
   * 意向客户ID
   */
  intentCustomerId: number;
  /**
   * 罚款金额
   */
  penaltyAmount: number;
  /**
   * 罚款类型 0:施工人员,1:供应商，2:工人
   */
  penaltyType: number;
  /**
   * 原因
   */
  reason: string;
  /**
   * 罚款类型=1,供应商ID
   */
  supplyId?: number;
  /**
   * 罚款类型=0,被罚款人ID
   */
  tagetUserId?: number;
  /**
   * 罚款类型=2,工人ID
   */
  workerId?: number;
  /**
   * 本地使用，选择被罚方的名称
   */
  selectedText: "";

  pics: string[];
};

export default () => {
  const { params } = useRouter<{
    intentCustomerId: `${number}`;
  }>();

  const intentCustomerId = Number(params.intentCustomerId);
  const [visible, { setTrue, setFalse }] = useBoolean();

  // 客户详情
  const { data } = useFetch<IntentCustomerData>(ApiCrm.customerDetail, {
    defaultParams: [{ intentCustomerId }],
    onAfter: (res) => res.intentCustomer,
  });

  // 审批流
  const [worflowIndex, setWorflowIndex] = useState(0)
  const [flowList, { loading: bindLoading, bind }] = useWorkflowDefinition({ typeCode: "FI_PenaltyBill" }, {
    onSuccess() {
      Taro.showToast({ title: "操作成功" });
      setTimeout(() => {
        Taro.redirectTo({
          url: `/packageProject/pages/fine/list?intentCustomerId=${intentCustomerId}`,
        });
      }, 1500);
    }
  })

  // 罚款表单
  const { loading, model, setModel, submit } = useForm<FormModel>(
    ApiFinance.fineAdd,
    {
      defaultModel: { penaltyType: 0, intentCustomerId, pics: [] },
      rules: {
        selectedText: { required: true, message: "请选择被罚对象" },
        penaltyAmount: { required: true, message: "请输入罚款金额" },
        reason: { required: true, message: "请输入罚款原因" },
      },
      onSuccess(res) {
        bind({
          businessId: res.PenaltyBillId + "",
          intentCustomerId
        }, worflowIndex)
      },
    }
  );

  // 设置处罚对象
  const handleSetTarget = (selected: Worker & Supplier & UserInfo) => {
    const obj = {
      // 0
      tagetUserId: 0,
      // 1
      supplyId: 0,
      // 2
      workerId: 0,

      selectedText: "",
    } as any;

    switch (model.penaltyType) {
      case 0:
        obj.selectedText = selected.user_name;
        obj.tagetUserId = selected.user_id;
        break;
      case 1:
        obj.selectedText = selected.supplyName;
        obj.supplyId = selected.supplyId;

        break;
      case 2:
        obj.selectedText = selected.workerName;
        obj.workerId = selected.workerId;
        break;
    }

    setModel(obj);
    setFalse();
  };

  // 上传成功
  const uploadSuccess = (ary: string[]) => {
    setModel({ pics: model.pics.concat(ary) });
  };

  const workflowSelected = flowList[worflowIndex]
  const popupType = tabItems[model.penaltyType]["key"];
  return (
    <>
      <Page
        footerSticky
        slotFooter={
          <ByButton
            className="w-2/3"
            size="large"
            loading={loading || bindLoading}
            onClick={() => submit()}
          >
            提交
          </ByButton>
        }
      >
        <Card className="m-3">
          <ByText bold className="text-lg">
            {data?.customerName}
          </ByText>
          <View className="mt-3 text-third text-sm">
            {data?.decorationFullAddress}
          </View>
        </Card>

        <ByCellGroup className="m-3">
          <ByCell label="被罚方" vertical requierd>
            <BySpace>
              {tabItems.map((item) => (
                <ByButton
                  key={item.value}
                  type={model.penaltyType == item.value ? "primary" : "info"}
                  variant={
                    model.penaltyType == item.value ? "solid" : "outline"
                  }
                  onClick={() =>
                    setModel({
                      penaltyType: item.value,
                      tagetUserId: undefined,
                      supplyId: undefined,
                      workerId: undefined,

                      selectedText: "",
                    })
                  }
                >
                  {item.label}
                </ByButton>
              ))}
            </BySpace>
          </ByCell>

          <ByCell label="被罚方对象" requierd vertical>
            <FormInput
              disabled
              value={model.selectedText}
              placeholder="选择被罚方对象"
              suffix={<ByIcon name="ArrowBottom" />}
              onClick={setTrue}
            />
          </ByCell>

          <ByCell label="处罚金额" align="right" vertical requierd>
            <FormInputNumber
              prefix="¥"
              precision={2}
              placeholder="输入处罚金额"
              onChange={(e) => setModel({ penaltyAmount: e })}
            />
          </ByCell>

          <ByCell label="处罚原因" vertical requierd>
            <FormInput
              type="textarea"
              value={model.reason}
              placeholder="输入处罚原因"
              onChange={(reason) => setModel({ reason })}
            />
          </ByCell>

          <ByCell label="处罚照片" vertical>
            <ByImageGroup
              urls={model.pics}
              showDelete
              onChange={res => setModel({ pics: res })}
              slotFooter={<Uploader onSuccess={uploadSuccess} />}
            />
          </ByCell>
        </ByCellGroup>

        <ByCellGroup className="m-3" title="审批">
          <ByCell label="选择审批流程" vertical requierd>
            <Picker
              range={flowList}
              rangeKey="workflowDefinitionName"
              value={worflowIndex}
              className="w-full"
              onChange={({ detail }) => setWorflowIndex(detail.value as number)}
            >
              <FormInput
                disabled
                placeholder="请选择"
                value={workflowSelected?.workflowDefinitionName}
                suffix={<ByIcon name="ArrowBottom" />}
              />
            </Picker>
          </ByCell>

          {workflowSelected?.steps.map((item) => (
            <ByStepsItem title={item.nodeName} key={item.nodeId}>
              <BySpace>
                {item.approvers?.map((item) => (
                  <ByTag size="small" variant="outline" key={item.actorId}>
                    {item.actorName}
                  </ByTag>
                ))}
              </BySpace>
            </ByStepsItem>
          ))}
        </ByCellGroup>

      </Page>

      <PageContainer round show={visible} onAfterLeave={setFalse}>
        {visible && (
          <PopupMember
            title="被罚款人"
            type={[popupType]}
            onCancel={setFalse}
            onConfirm={handleSetTarget}
          />
        )}
      </PageContainer>
    </>
  );
};
